package com.review.Test.Future;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *future模式的缺点：分支线程遇到异常是，主线程调用get()时会卡死,所以分支线程一定要用try-catch
 *
 */
public class futureTest1 {

	public static void main(String[] args) throws Exception {
		//		noUseFutureTask();
		useFutureTask();
	}

	private static void useFutureTask() throws InterruptedException,
	ExecutionException {
		//自定义线程池
		ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, 
				new ArrayBlockingQueue<Runnable>(5), new RejectedExecutionHandler() {
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				//记录一下谁被拒绝
				System.out.println(r.toString() + "   别拒绝执行。。。");
			}
		});

		MyJob myJob = new MyJob("query");
		FutureTask<String> futureTask = new FutureTask<>(myJob);

		System.out.println("主线程");
		Future<?> submit = pool.submit(futureTask);
		System.out.println("FutureTask:   "+futureTask.get());
		System.out.println("Future:   "+submit.get());
		System.out.println("执行完毕。。。");

		pool.shutdown();
	}

	private static void noUseFutureTask() throws InterruptedException,
	ExecutionException {
		//自定义线程池
		ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, 
				new ArrayBlockingQueue<Runnable>(5), new RejectedExecutionHandler() {
			@Override
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				//记录一下谁被拒绝
				System.out.println(r.toString() + "   别拒绝执行。。。");
			}
		});

		MyJob myJob = new MyJob("query");
		Future<String> submit = pool.submit(myJob);

		System.out.println("主线程");
		String string = submit.get();
		System.out.println("结果： " + string);

		pool.shutdown();
	}

}

class MyJob implements Callable<String> {

	private String name;

	public MyJob(String name) {
		super();
		this.name = name;
	}

	@Override
	public String toString() {
		return "MyJob [name=" + name + "]";
	}

	@Override
	public String call() throws Exception {
		try {
			Thread.sleep(2000);
			int i = 1/0;
			Thread.sleep(3000);
		} catch (Exception e) {
		}
		return name + "   执行完毕。。。";
	}

}
